package com.example.hasayam.ocrtest3;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSIONS_REQUEST = 108;
    private static final String DATA_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    private static final String tessdata = DATA_PATH + File.separator + "tessdata";
    private static String DEFAULT_LANGUAGE = "uig";
    private static String DEFAULT_LANGUAGE_NAME = DEFAULT_LANGUAGE + ".traineddata";
    private static String LANGUAGE_PATH = tessdata + File.separator + DEFAULT_LANGUAGE_NAME;

    Context context = this;

    boolean Madina;
    CameraSurfaceView cameraSurfaceView;
    TextView tx;
    ImageView img;
    RadioGroup rg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        requestMultiplePermissions();
        copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
        cameraSurfaceView = findViewById(R.id.surface);
        tx = findViewById(R.id.tx);
        img = findViewById(R.id.img);
        rg = findViewById(R.id.rg);

        //选择语言并导入相关库
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radioButtonUg:{
                        DEFAULT_LANGUAGE = "uig";
                        DEFAULT_LANGUAGE_NAME = DEFAULT_LANGUAGE + ".traineddata";
                        LANGUAGE_PATH = tessdata + File.separator + DEFAULT_LANGUAGE_NAME;
                        copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                    }break;
                    case R.id.radioButtonCn:{
                        DEFAULT_LANGUAGE = "chi_sim";
                        DEFAULT_LANGUAGE_NAME = DEFAULT_LANGUAGE + ".traineddata";
                        LANGUAGE_PATH = tessdata + File.separator + DEFAULT_LANGUAGE_NAME;
                        copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                    }break;
                }
            }
        });

    }

    //申请权限
    private void requestMultiplePermissions() {

        String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        String cameraPermission = Manifest.permission.CAMERA;

        int hasStoragePermission = ActivityCompat.checkSelfPermission(this, storagePermission);
        int hasCameraPermission = ActivityCompat.checkSelfPermission(this, cameraPermission);

        List<String> permissions = new ArrayList<>();
        if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(storagePermission);
        }

        if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(cameraPermission);
        }

        if (!permissions.isEmpty()) {
            String[] params = permissions.toArray(new String[permissions.size()]);
            ActivityCompat.requestPermissions(this, params, PERMISSIONS_REQUEST);
        }
    }

    //获取相机的照片一张，我自己写的，很屎的一段代码，不用太纠结。
    public void madina(View view) {
        final Bitmap[] bt = {null};
        Madina = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                cameraSurfaceView.capture();
                while(Madina){
                    bt[0] = cameraSurfaceView.getBt();
                    if (bt[0] !=null) {
                        //得到的bitmap传到识别算法中。
                        startImageClassifier(bt[0]);
                        bt[0] = null;
                        Madina = false;
                    }
                }
            }
        }).start();
    }

    //识别算法，开始工作了。
    private void startImageClassifier(final Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override

            public void run() {

                Bitmap b = bitmap;
                b = adjustPhotoRotation(b,90);
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tx.setText("正在处理");
                    }
                });
                final Bitmap finalB1 = b;
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        img.setImageBitmap(finalB1);
                    }
                });

                b = ImageFilter.grayScale(b);
                b = ImageFilter.binaryzation(b);
                final Bitmap finalB = b;
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        img.setImageBitmap(finalB);
                    }
                });
                TessBaseAPI baseApi = new TessBaseAPI();
                if (baseApi.init(DATA_PATH, DEFAULT_LANGUAGE)) {
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tx.setText("识别中");
                        }
                    });
                    //设置识别模式
                    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO);
                    //设置要识别的图片
                    baseApi.setImage(b);
                    //开始识别
                    final String str = baseApi.getUTF8Text();
                    baseApi.clear();
                    baseApi.end();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (str.equals(""))
                            {
                                tx.setText("无内容");
                            }
                            else
                                tx.setText(str);
                        }
                    });
                }
            }
        }).start();
    }
    /**
     * 请求到权限后在这里复制识别库
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                }
                break;
            default:
                break;
        }
    }
    /**
     * 将assets中的识别库复制到SD卡中
     *
     * @param path 要存放在SD卡中的 完整的文件名。这里是"/storage/emulated/0//tessdata/chi_sim.traineddata"
     * @param name assets中的文件名 这里是 "chi_sim.traineddata"
     */
    public void copyToSD(final String path, final String name) {
        //如果存在就删掉
        new Thread(new Runnable() {
            @Override
            public void run() {
                File f = new File(path);
                if (f.exists()) {
                    f.delete();
                }
                if (!f.exists()) {
                    File p = new File(f.getParent());
                    if (!p.exists()) {
                        p.mkdirs();
                    }
                    try {
                        f.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                InputStream is = null;
                OutputStream os = null;
                try {
                    is = context.getAssets().open(name);
                    File file = new File(path);
                    os = new FileOutputStream(file);
                    byte[] bytes = new byte[2048];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        os.write(bytes, 0, len);
                    }
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                        if (os != null)
                            os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
    /**
     * 相机出来的bitmap需要旋转90°才能正过来
     * @param bitmap
     * @param orientationDegree 0 - 360 范围
     * @return
     */
    Bitmap adjustPhotoRotation(Bitmap bitmap, int orientationDegree) {
        Matrix matrix = new Matrix();
        matrix.setRotate(orientationDegree, (float) bitmap.getWidth() / 2,
                (float) bitmap.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bitmap.getHeight();
            targetY = 0;
        } else {
            targetX = bitmap.getHeight();
            targetY = bitmap.getWidth();
        }
        final float[] values = new float[9];
        matrix.getValues(values);
        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];
        matrix.postTranslate(targetX - x1, targetY - y1);
        Bitmap canvasBitmap = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(canvasBitmap);
        canvas.drawBitmap(bitmap, matrix, paint);
        return canvasBitmap;
    }
}
